//
//  LEERefreshView.swift
//  SinaWeibo
//
//  Created by 李江波 on 2016/11/19.
//  Copyright © 2016年 lijiangbo. All rights reserved.
//

import UIKit

private let refreshHight : CGFloat = 60
//枚举状态
enum Rstatus : Int {
    case normal = 0
    case already
    case refreshing
}


class LEERefreshView: UIControl {

    var superView : UIScrollView?
    
    var refreahStatus: Rstatus = .normal {
        didSet{
        
            
            
            switch refreahStatus {
            case .normal:
                
                self.indicator.stopAnimating()
                self.leftImage.isHidden = false
                self.rightLbl.text = "下拉刷新"
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.leftImage.transform = CGAffineTransform.identity
                })
                //判断是否首次加载
                if oldValue == .refreshing {
                    
                    UIView.animate(withDuration: 0.25, animations: {
                        
                        self.superView!.contentInset.top = self.superView!.contentInset.top - refreshHight
                    })
                    
                }
            case .already:
                self.rightLbl.text = "松手刷新"
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.leftImage.transform = CGAffineTransform.init(rotationAngle: CGFloat(M_PI))
                })
            case .refreshing:
                
                self.leftImage.isHidden = true
                self.rightLbl.text = "正在刷新哦。。"
                self.indicator.startAnimating()
                //如何触发事件
                self.sendActions(for: .valueChanged)
                //正在刷新状态有悬停的效果 修改contentInset.top
                UIView.animate(withDuration: 0.25, animations: {
                    
                    self.superView!.contentInset.top = self.superView!.contentInset.top + refreshHight
                })
                
                
            }
        }
    }
    
    func endRefresh() {
        
        //延迟执行，停留时间久
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            
            self.refreahStatus = .normal
        }
        
    }
    
    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refreshHight, width: kUISCRRENW, height: refreshHight)
        
        super.init(frame: rect)
        backgroundColor = arcColor()
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        addSubview(bgImg)
        addSubview(leftImage)
        addSubview(rightLbl)
        addSubview(indicator)
        
        bgImg.snp.makeConstraints { (make) in
            
            make.left.right.bottom.equalTo(self)
        }
        
        rightLbl.snp.makeConstraints { (make) in
            
            make.centerX.equalTo(self).offset(10)
            make.centerY.equalTo(self)
        }
        leftImage.snp.makeConstraints { (make) in
            
            make.right.equalTo(rightLbl.snp.left).offset(-5)
            make.centerY.equalTo(self)
        }
        indicator.snp.makeConstraints { (make) in
            
            make.center.equalTo(leftImage)
        }
        
    }
    
    
    
    lazy var leftImage = UIImageView(image: #imageLiteral(resourceName: "tableview_pull_refresh"))
    lazy var rightLbl = UILabel(title: "下拉刷新", textColor: UIColor.orange, font: 14)
    lazy var indicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
    //背景图片
    lazy var bgImg = UIImageView(image: #imageLiteral(resourceName: "refreshbg"))
    
    override func willMove(toSuperview newSuperview: UIView?) {
        super.willMove(toSuperview: newSuperview)
        let scrollView : UIScrollView = newSuperview as! UIScrollView
        
        superView = scrollView
        ///kvo 监听上下拉动距离
        self.superView!.addObserver(self, forKeyPath: "contentOffset", options: [.new], context: nil)
    }
    
    //处理监听事件
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        let offsetY = self.superView?.contentOffset.y ?? 0
        let changeY = -((self.superView?.contentInset.top)! + refreshHight)
        
        if superView!.isDragging {
            
            if refreahStatus == .already && offsetY > changeY {
                //准备状态
                refreahStatus = .normal
                
            }else if refreahStatus == .normal && offsetY < changeY {
                //就绪状态
                refreahStatus = .already
                
            }
        }else{
        
            if refreahStatus == .already {
                //刷新状态
                refreahStatus = .refreshing
            }
        
        }
    }
    
    deinit {
        superView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
}










